import { getAgentInfo, getAgentUserId } from '@/api/agent'

/**
 * 从房源对象获取经纪人ID，支持多种可能的字段名
 * @param {Object} house - 房源对象
 * @returns {number|string|null} - 经纪人ID或null
 */
function getAgentId(house) {
  if (!house) return null
  
  // 尝试从多个可能的字段获取经纪人ID
  return house.agentId || 
         (house.agent && (house.agent.id || house.agent.agentId)) || 
         house.agent_id || 
         (house.agentInfo && (house.agentInfo.id || house.agentInfo.agentId))
}

/**
 * 获取经纪人对应的聊天用户ID
 * @param {Object} agentInfo - 经纪人信息对象
 * @param {string|number} agentId - 经纪人ID
 * @returns {Promise<string|number|null>} - 用于聊天的用户ID
 */
export async function getChatUserId(agentInfo, agentId) {
  if (!agentInfo && !agentId) return null;
  
  // 1. 首先尝试从经纪人信息对象中获取用户ID
  if (agentInfo) {
    const directUserId = agentInfo.userId || agentInfo.user_id || agentInfo.chatUserId;
    if (directUserId) {
      console.log('从经纪人信息中直接获取到聊天用户ID:', directUserId);
      return directUserId;
    }
  }
  
  // 2. 如果经纪人信息中没有用户ID且提供了经纪人ID，尝试通过专门的API获取
  if (agentId) {
    try {
      const response = await getAgentUserId(agentId);
      console.log('获取经纪人用户ID API响应:', response);
      
      if (response.code === 200 && response.data) {
        // 处理不同的响应格式
        const userId = response.data.userId || response.data.user_id || response.data;
        if (userId) {
          console.log('通过API获取到用户ID:', userId);
          return userId;
        }
      }
    } catch (error) {
      console.error('获取经纪人用户ID失败:', error);
    }
    
    // 3. 如果通过API获取失败，则假设用户ID与经纪人ID相同
    console.warn('未能获取到专门的聊天用户ID，使用经纪人ID作为默认值:', agentId);
    return agentId;
  }
  
  return null;
}

/**
 * 为房源列表补充经纪人信息
 * @param {Array} houseList - 房源列表数据
 * @returns {Promise<Array>} - 补充了经纪人信息的房源列表
 */
export async function enrichHousesWithAgentInfo(houseList) {
  if (!houseList || !houseList.length) return houseList

  try {
    // 从房源中提取所有不重复的经纪人ID
    const agentIds = Array.from(new Set(
      houseList.filter(house => getAgentId(house)).map(house => getAgentId(house))
    ))
    
    if (!agentIds.length) return houseList
    
    console.log('需要获取的经纪人ID列表:', agentIds)
    
    // 保存经纪人信息的Map
    const agentInfoMap = {}
    
    // 并行请求所有经纪人信息
    const agentPromises = agentIds.map(agentId => 
      getAgentInfo(agentId)
        .then(res => {
          if (res.code === 200 && res.data) {
            agentInfoMap[agentId] = res.data
            
            // 尝试获取聊天用户ID
            return getChatUserId(res.data, agentId).then(chatUserId => {
              if (chatUserId) {
                agentInfoMap[agentId].chatUserId = chatUserId;
              }
              return res;
            });
          }
          return res
        })
        .catch(err => {
          console.error(`获取经纪人(ID:${agentId})信息失败:`, err)
          return null
        })
    )
    
    await Promise.all(agentPromises)
    
    // 将经纪人信息合并到房源数据中
    return houseList.map(house => {
      const agentId = getAgentId(house)
      const agentInfo = agentId ? agentInfoMap[agentId] : null
      
      if (!agentInfo) return house
      
      return {
        ...house,
        // 确保agentId字段存在
        agentId: agentId,
        // 添加聊天用户ID
        chatUserId: agentInfo.chatUserId || agentId,
        // 如果API返回了这些字段就用API返回的，否则用经纪人信息中的，都没有则用默认值
        agentName: house.agentName || (agentInfo.name || agentInfo.realName) || '暂无经纪人',
        agentAvatar: house.agentAvatar || agentInfo.avatar || '/images/agent/avatar-default.png',
        agentTitle: house.agentTitle || agentInfo.title || '房产顾问',
        agentExperience: house.agentExperience || agentInfo.yearsOfExperience || 0,
        agentDeals: house.agentDeals || agentInfo.totalSales || 0,
        agentViews: house.agentViews || agentInfo.totalViews || 0,
        agentRating: house.agentRating || agentInfo.rating || 5.0,
        agentServiceArea: house.agentServiceArea || agentInfo.serviceArea || '全城',
        agentExpertise: house.agentExpertise || agentInfo.expertise || '',
        agentPhone: house.agentPhone || agentInfo.phone || '',
        agentWechat: house.agentWechat || agentInfo.wechat || '',
        // 创建统一的agentStats结构
        agentStats: {
          experience: house.agentExperience || agentInfo.yearsOfExperience || 0,
          deals: house.agentDeals || agentInfo.totalSales || 0,
          rating: house.agentRating || agentInfo.rating || 5.0,
          views: house.agentViews || agentInfo.totalViews || 0
        }
      }
    })
  } catch (error) {
    console.error('补充经纪人信息失败:', error)
    return houseList // 如果失败，返回原始数据
  }
}

/**
 * 为单个房源对象补充经纪人信息
 * @param {Object} house - 单个房源数据对象
 * @returns {Promise<Object>} - 补充了经纪人信息的房源对象
 */
export async function enrichHouseWithAgentInfo(house) {
  if (!house) return house
  
  // 获取经纪人ID
  const agentId = getAgentId(house)
  if (!agentId) return house
  
  try {
    console.log(`尝试获取经纪人(ID:${agentId})信息`)
    // 获取经纪人信息
    const res = await getAgentInfo(agentId)
    
    if (res.code !== 200 || !res.data) return house
    
    const agentInfo = res.data
    
    // 获取聊天用户ID
    const chatUserId = await getChatUserId(agentInfo, agentId);
    
    // 将经纪人信息合并到房源数据中
    return {
      ...house,
      // 确保agentId字段存在
      agentId: agentId,
      // 添加聊天用户ID
      chatUserId: chatUserId || agentId,
      // 如果API返回了这些字段就用API返回的，否则用经纪人信息中的，都没有则用默认值
      agentName: house.agentName || (agentInfo.name || agentInfo.realName) || '暂无经纪人',
      agentAvatar: house.agentAvatar || agentInfo.avatar || '/images/agent/avatar-default.png',
      agentTitle: house.agentTitle || agentInfo.title || '房产顾问',
      agentExperience: house.agentExperience || agentInfo.yearsOfExperience || 0,
      agentDeals: house.agentDeals || agentInfo.totalSales || 0,
      agentViews: house.agentViews || agentInfo.totalViews || 0,
      agentRating: house.agentRating || agentInfo.rating || 5.0,
      agentServiceArea: house.agentServiceArea || agentInfo.serviceArea || '全城',
      agentExpertise: house.agentExpertise || agentInfo.expertise || '',
      agentPhone: house.agentPhone || agentInfo.phone || '',
      agentWechat: house.agentWechat || agentInfo.wechat || '',
      // 创建统一的agentStats结构
      agentStats: {
        experience: house.agentExperience || agentInfo.yearsOfExperience || 0,
        deals: house.agentDeals || agentInfo.totalSales || 0,
        rating: house.agentRating || agentInfo.rating || 5.0,
        views: house.agentViews || agentInfo.totalViews || 0
      }
    }
  } catch (error) {
    console.error(`获取经纪人(ID:${agentId})信息失败:`, error)
    return house // 如果失败，返回原始数据
  }
} 